package com.vercon.moensmart.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.vercon.common.utils.LogUtils
import com.vercon.moensmart.MainActivity
import com.vercon.moensmart.event.AppDeleteEvent
import com.vercon.moensmart.event.InstalledEvent
import org.greenrobot.eventbus.EventBus

class InstallBroadcast : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        LogUtils.i("InstallBroadcast", intent.action)
        if (Intent.ACTION_PACKAGE_REPLACED == intent.action) {
            //有应用被替换
            LogUtils.d("有应用被替换")
            val packageName = intent.data!!.schemeSpecificPart
            if (packageName == context.packageName) {
                //自身APP更新
                LogUtils.d("isUpdate true")
                val it = Intent(context, MainActivity::class.java)
                it.action = Intent.ACTION_VIEW
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(it)
            } else {
                LogUtils.d("isUpdate false")
            }
        } else if (Intent.ACTION_PACKAGE_ADDED == intent.action) {
            //有应用被添加，第一次安装，和更新安装都跑
            LogUtils.d("有应用被添加")
            EventBus.getDefault().post(InstalledEvent(true))
        } else if (Intent.ACTION_PACKAGE_REMOVED == intent.action) {
            //卸载APP回调
            EventBus.getDefault().post(AppDeleteEvent(true))
        } else {
            LogUtils.i("InstallBroadcast", intent.action)
        }
    }
}